﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using XQ.Framework.core;
using XQ.Framework.common;
using XQ.Framework.model;

namespace XQ.Framework.io
{
    /// <summary>
    /// 用来上传文件的类
    /// authour:WJ
    /// </summary>
    public class FileUpload
    {
        #region 属性
        private readonly string SEP = IOHelper.GetSysPathSeparator();
        public FileUpload()
        {
            MaxSize = 1024 * 1024;
            AllowFileType = new string[] { ".jpg", ".jpeg", ".png", ".gif" };
        }
        public int MaxSize { get; set; }
        public string[] AllowFileType { get; set; }
        #endregion

        #region 私有方法
        /// <summary>
        /// 获取一个新的文件模型
        /// </summary>
        /// <returns></returns>
        private UpLoadFileModelBase PrepareNewFile(HttpPostedFile http_file, string save_path)
        {
            UpLoadFileModelBase model = new UpLoadFileModelBase();
            model.CanUpload = model.SuccessUpload = false;
            try
            {
                if (http_file == null || http_file.InputStream == null)
                {
                    model.Info = "http文件流为空";
                    return model;
                }
                if (http_file.ContentLength > MaxSize)
                {
                    model.Info = "文件太大了";
                    return model;
                }
                save_path = ConvertHelper.getString(save_path);
                string file_name = ConvertHelper.getString(http_file.FileName);
                string file_extesion = IOHelper.getFileExtension(file_name);
                //检查存储路径是否存在，不存在就创建
                DateTime dt = DateTime.Now;
                string YEAR = dt.Year.ToString(), DATE = dt.Month + "_" + dt.Day;
                save_path += (save_path.EndsWith(SEP) ? "" : SEP) + YEAR + SEP + DATE + SEP;
                if (!Directory.Exists(save_path))
                {
                    Directory.CreateDirectory(save_path);
                }
                //////////////////////////////////////////////////
                if (!AllowFileType.Contains(file_extesion))//检查文件格式
                {
                    model.Info = "文件格式不允许";
                    return model;
                }
                //如果文件存在就用guid和随机字符胡乱命名
                while (File.Exists(save_path + file_name))
                {
                    file_name = Com.getUUID() + file_extesion;
                }
                //文件名称（xxx.jpg）
                model.FileName = file_name;
                //文件后缀(.jpg)
                model.FileExtension = file_extesion;
                //本地存储文件夹路径
                model.DirectoryPath = save_path;
                //浏览器相对路径
                model.WebPath = YEAR + "/" + DATE + "/";
                //本地存储绝对文件路径
                model.FilePath = model.DirectoryPath + model.FileName;
                model.CanUpload = true;
            }
            catch (Exception e)
            {
                model.Info = e.Message;
                return model;
            }
            return model;
        }
        #endregion

        #region 提供调用的方法
        /// <summary>
        /// 上传单个文件
        /// </summary>
        /// <param name="http_file"></param>
        /// <param name="save_path"></param>
        /// <returns></returns>
        public UpLoadFileModelBase UploadSingleFile(HttpPostedFile http_file, string save_path)
        {
            FileStream fs = null;
            try
            {
                //获取一个新的文件模型
                UpLoadFileModelBase model = PrepareNewFile(http_file, save_path);
                fs = new FileStream(model.FilePath, FileMode.Create, FileAccess.Write);
                //循环写数据，结束后关闭输入输出流
                if ((fs = IOHelper.WritePostFileToFileStreamAndCloseStream(http_file, fs)) != null)
                {
                    model.SuccessUpload = true;
                }
                return model;
            }
            catch (Exception e)
            {
                return null;
            }
        }
        /// <summary>
        /// 上传单个文件
        /// </summary>
        /// <param name="http_files"></param>
        /// <param name="key"></param>
        /// <param name="save_path"></param>
        /// <returns></returns>
        public UpLoadFileModelBase UploadSingleFile(HttpFileCollection http_files, string key, string save_path)
        {
            if (http_files == null || http_files.Count == 0) { return null; }

            return this.UploadSingleFile(http_files[key], save_path);
        }
        /// <summary>
        /// 上传所有文件
        /// </summary>
        /// <returns>返回上传后的文件信息</returns>
        public List<UpLoadFileModelBase> UploadAllFile(HttpFileCollection http_files, string save_path)
        {
            if (http_files == null || http_files.Count == 0) { return null; }

            List<UpLoadFileModelBase> filelist = new List<UpLoadFileModelBase>();

            int count = http_files.Count;
            for (int i = 0; i < count; i++)
            {
                filelist.Add(this.UploadSingleFile(http_files[i], save_path));
            }
            return filelist;
        }
        #endregion

    }
}

